package com.uwo.commons.kits;
import java.io.UnsupportedEncodingException;

/**
 * base64的工具类
 * @author hao.yan
 */
public class Base64Kits {

    private static final byte[] encodingTable = {
            (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E',
            (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J',
            (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O',
            (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T',
            (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y',
            (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd',
            (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i',
            (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',
            (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's',
            (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x',
            (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2',
            (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
            (byte) '8', (byte) '9', (byte) '+', (byte) '/'
    };

    private static final byte[] decodingTable;
    static {
        decodingTable = new byte[128];
        for (int i = 0; i < 128; i++)
            decodingTable[i] = (byte) -1;
        for (int i = 'A'; i <= 'Z'; i++)
            decodingTable[i] = (byte) (i - 'A');
        for (int i = 'a'; i <= 'z'; i++)
            decodingTable[i] = (byte) (i - 'a' + 26);
        for (int i = '0'; i <= '9'; i++)
            decodingTable[i] = (byte) (i - '0' + 52);
        decodingTable['+'] = 62;
        decodingTable['/'] = 63;
    }

    /**
     * 每三个字节加密转成四个字节，加密后不满足四个字节的用（=）填补
     * @param data
     * @return
     */
    public static byte[] encode(byte[] data) {
        int modulus = data.length % 3;
        int len = (( modulus == 0 ) ? (data.length / 3) :( (data.length / 3) + 1 )) ;
        byte [] bytes = new byte[(4 * len)];
        for (int i = 0, j = 0; j < bytes.length; i += 3, j += 4) {
            bytes[j] = encodingTable[((data[i] & 0xff) >>> 2) & 0x3f];
            if(data.length - (i + 3) >= 0){
                bytes[j + 1] = encodingTable[(((data[i] & 0xff) << 4) | ((data[i + 1] & 0xff) >>> 4)) & 0x3f];
                bytes[j + 2] = encodingTable[(((data[i + 1] & 0xff) << 2) | ((data[i + 2] & 0xff) >>> 6)) & 0x3f];
                bytes[j + 3] = encodingTable[(data[i + 2] & 0xff) & 0x3f];
            }else if(modulus == 2){
                bytes[j + 1] = encodingTable[(((data[i] & 0xff) << 4) | ((data[i + 1] & 0xff) >>> 4)) & 0x3f];
                bytes[j + 2] = encodingTable[((data[i + 1] & 0xff) << 2) & 0x3f];
                bytes[j + 3] = (byte) '=';
            }else if(modulus == 1){
                bytes[j + 1] = encodingTable[((data[i] & 0xff) << 4) & 0x3f];
                bytes[j + 2] = (byte) '=';
                bytes[j + 3] = (byte) '=';
            }
        }
        return bytes;
    }

    public static byte[] encode(String data) throws UnsupportedEncodingException{
        return encode(data.getBytes("UTF-8"));
    }

    /**
     * base64解密
     * 每四个字节解密成三个字节
     * @param data
     * @return
     */
    public static byte[] decode(byte[] data) {
        int increment = ( data[data.length - 2] == '=' ) ? 1 :(( data[data.length - 1] == '=' ) ? 2 : 0 );
        int len = (increment > 0) ? (((( data.length / 4 ) - 1 ) * 3 ) + increment ): (( data.length / 4 ) * 3);
        byte[] bytes = new byte[len];
        for (int i = 0, j = 0; i < data.length; i += 4, j += 3) {
            bytes[j] = (byte) ((decodingTable[data[i]] << 2) | (decodingTable[data[i + 1]] >> 4));
            if(data[i + 2] == '=')
                break;
            bytes[j + 1] = (byte) ((decodingTable[data[i + 1]] << 4) | (decodingTable[data[i + 2]] >> 2));
            if(data[i + 3] == '=')
                break;
            bytes[j + 2] = (byte) ((decodingTable[data[i + 2]] << 6) | decodingTable[data[i + 3]]);
        }
        return bytes;
    }

    public static byte[] decode(String data) throws UnsupportedEncodingException{
        return decode(data.getBytes("UTF-8"));
    }

    /**
     * 验证是否是base64
     * @param bytes
     * @return
     */
    public static boolean isBase64(byte[] bytes){
        for (byte b:bytes)
            if(!isValidBase64Byte(b))
                return false;
        return true;
    }

    /**
     * 验证是否base64字节
     * @param b
     * @return
     */
    private static boolean isValidBase64Byte(byte b) {
        if (b == '=')
            return true;
        else if ((b < 0) || (b >= 128))
            return false;
        else if (decodingTable[b] == -1)
            return false;
        return true;
    }

}
